package com.bigger.utils;

import com.bigger.properties.MinIOProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
/**
 * 此工具类较为特殊且只有此端使用
 * 所以未写入xhdn-common中
 */
public class MinIOUtil {
    @Autowired
    private MinIOProperties minIOProperties;
    @Autowired
    private MinioClient client;

    /**
     * 上传文件
     * @param fileName 文件名字
     * @param fileType 文件类型
     * @param inputStream 文件输入流
     * @return
     */
    public String uploadFile(String fileName, String fileType, InputStream inputStream){
        try {
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName)
                .bucket(minIOProperties.getBucketName())
                .contentType(fileType)
                .stream(inputStream, inputStream.available(), -1)
                .build();
        client.putObject(putObjectArgs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                inputStream.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return minIOProperties.getUrl()+"/"+minIOProperties.getBucketName()+"/"+fileName;
    }

    /**
     * 删除文件
     * @param fileName
     */
    public boolean deleteFile(String fileName){
        RemoveObjectArgs removeObject= RemoveObjectArgs.builder()
                .object(fileName)
                .bucket(minIOProperties.getBucketName())
                .build();
        try {
            client.removeObject(removeObject);
            return true;
        } catch (Exception e){
            return false;
        }
    }
}
